<template>
  <div class="report-designer">
    <!-- 顶部工具栏 -->
    <div class="designer-header">
      <div class="header-left">
        <el-input 
          v-model="reportName" 
          placeholder="报表名称" 
          style="width: 300px;"
          clearable
        />
        <el-button type="primary" @click="handleSave">
          <el-icon><DocumentAdd /></el-icon>
          保存
        </el-button>
        <el-button @click="handlePreview">
          <el-icon><View /></el-icon>
          预览
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
      <div class="header-right">
        <el-button @click="handleUndo" :disabled="history.current <= 0">
          <el-icon><RefreshLeft /></el-icon>
          撤销
        </el-button>
        <el-button @click="handleRedo" :disabled="history.current >= history.stack.length - 1">
          <el-icon><RefreshRight /></el-icon>
          重做
        </el-button>
        <el-button type="success" @click="handleAIGenerate">
          <el-icon><MagicStick /></el-icon>
          AI生成
        </el-button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="designer-body">
      <!-- 左侧组件库 -->
      <div class="designer-left">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="数据源" name="datasource">
            <div class="component-list">
              <el-collapse v-model="activeDatasource">
                <el-collapse-item title="数据库表" name="1">
                  <div 
                    v-for="table in databaseTables" 
                    :key="table.id"
                    class="component-item"
                    draggable="true"
                    @dragstart="handleDragStart($event, 'table', table)"
                  >
                    <el-icon><Document /></el-icon>
                    <span>{{ table.name }}</span>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="SQL查询" name="2">
                  <el-button type="primary" size="small" @click="sqlDialogVisible = true">
                    <el-icon><Plus /></el-icon>
                    新建查询
                  </el-button>
                  <div 
                    v-for="query in sqlQueries" 
                    :key="query.id"
                    class="component-item"
                    draggable="true"
                    @dragstart="handleDragStart($event, 'query', query)"
                  >
                    <el-icon><Connection /></el-icon>
                    <span>{{ query.name }}</span>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="API接口" name="3">
                  <el-button type="primary" size="small" @click="apiDialogVisible = true">
                    <el-icon><Plus /></el-icon>
                    新建接口
                  </el-button>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-tab-pane>

          <el-tab-pane label="图表组件" name="charts">
            <div class="component-list">
              <div 
                v-for="chart in chartComponents" 
                :key="chart.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, 'chart', chart)"
              >
                <el-icon>
                  <component :is="chart.icon" />
                </el-icon>
                <span>{{ chart.label }}</span>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="基础组件" name="components">
            <div class="component-list">
              <div 
                v-for="comp in basicComponents" 
                :key="comp.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart($event, 'component', comp)"
              >
                <el-icon>
                  <component :is="comp.icon" />
                </el-icon>
                <span>{{ comp.label }}</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 中间画布区域 -->
      <div class="designer-canvas">
        <div class="canvas-toolbar">
          <span>画布尺寸: </span>
          <el-select v-model="canvasSize" size="small" style="width: 150px;">
            <el-option label="A4竖向" value="a4-portrait" />
            <el-option label="A4横向" value="a4-landscape" />
            <el-option label="自适应" value="auto" />
            <el-option label="自定义" value="custom" />
          </el-select>
          <el-divider direction="vertical" />
          <span>缩放: </span>
          <el-slider 
            v-model="canvasZoom" 
            :min="50" 
            :max="200" 
            :step="10"
            style="width: 150px; margin: 0 10px;"
          />
          <span>{{ canvasZoom }}%</span>
        </div>

        <div 
          class="canvas-area"
          :style="{ transform: `scale(${canvasZoom / 100})` }"
          @drop="handleDrop"
          @dragover.prevent
        >
          <div 
            v-for="(item, index) in canvasItems" 
            :key="item.id"
            class="canvas-item"
            :class="{ active: selectedItem === item.id }"
            :style="{
              left: item.x + 'px',
              top: item.y + 'px',
              width: item.width + 'px',
              height: item.height + 'px'
            }"
            @click="handleSelectItem(item.id)"
          >
            <!-- 图表组件 -->
            <div v-if="item.type === 'chart'" class="item-chart">
              <div class="chart-placeholder">
                {{ item.chartType }} 图表
              </div>
            </div>

            <!-- 表格组件 -->
            <div v-else-if="item.type === 'table'" class="item-table">
              <el-table :data="item.mockData" border size="small">
                <el-table-column 
                  v-for="col in item.columns" 
                  :key="col.prop"
                  :prop="col.prop" 
                  :label="col.label"
                />
              </el-table>
            </div>

            <!-- 文本组件 -->
            <div v-else-if="item.type === 'text'" class="item-text">
              {{ item.content }}
            </div>

            <!-- 标题组件 -->
            <div v-else-if="item.type === 'title'" class="item-title">
              <h2>{{ item.content }}</h2>
            </div>

            <!-- 图片组件 -->
            <div v-else-if="item.type === 'image'" class="item-image">
              <img :src="item.src" v-if="item.src" />
              <div v-else class="image-placeholder">图片</div>
            </div>

            <!-- 删除按钮 -->
            <div class="item-remove" @click.stop="handleRemoveItem(index)">
              <el-icon><Close /></el-icon>
            </div>

            <!-- 调整大小手柄 -->
            <div class="resize-handle"></div>
          </div>

          <!-- 空状态 -->
          <div v-if="canvasItems.length === 0" class="empty-canvas">
            <el-empty description="拖拽左侧组件到画布开始设计报表" />
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="designer-right">
        <el-tabs v-model="rightTab">
          <el-tab-pane label="属性" name="properties">
            <div class="properties-panel" v-if="selectedItemData">
              <el-form label-width="80px" size="small">
                <el-form-item label="组件类型">
                  <el-input :value="selectedItemData.type" disabled />
                </el-form-item>
                
                <el-divider>位置和尺寸</el-divider>
                
                <el-form-item label="X坐标">
                  <el-input-number v-model="selectedItemData.x" :min="0" />
                </el-form-item>
                
                <el-form-item label="Y坐标">
                  <el-input-number v-model="selectedItemData.y" :min="0" />
                </el-form-item>
                
                <el-form-item label="宽度">
                  <el-input-number v-model="selectedItemData.width" :min="50" />
                </el-form-item>
                
                <el-form-item label="高度">
                  <el-input-number v-model="selectedItemData.height" :min="50" />
                </el-form-item>

                <!-- 图表特定属性 -->
                <template v-if="selectedItemData.type === 'chart'">
                  <el-divider>图表设置</el-divider>
                  
                  <el-form-item label="图表类型">
                    <el-select v-model="selectedItemData.chartType">
                      <el-option label="柱状图" value="bar" />
                      <el-option label="折线图" value="line" />
                      <el-option label="饼图" value="pie" />
                      <el-option label="散点图" value="scatter" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="标题">
                    <el-input v-model="selectedItemData.title" />
                  </el-form-item>
                </template>

                <!-- 文本特定属性 -->
                <template v-if="selectedItemData.type === 'text' || selectedItemData.type === 'title'">
                  <el-divider>文本设置</el-divider>
                  
                  <el-form-item label="内容">
                    <el-input v-model="selectedItemData.content" type="textarea" />
                  </el-form-item>
                  
                  <el-form-item label="字体大小">
                    <el-input-number v-model="selectedItemData.fontSize" :min="12" :max="72" />
                  </el-form-item>
                  
                  <el-form-item label="颜色">
                    <el-color-picker v-model="selectedItemData.color" />
                  </el-form-item>
                </template>

                <!-- 表格特定属性 -->
                <template v-if="selectedItemData.type === 'table'">
                  <el-divider>表格设置</el-divider>
                  
                  <el-form-item label="数据源">
                    <el-select v-model="selectedItemData.datasource">
                      <el-option label="订单表" value="orders" />
                      <el-option label="产品表" value="products" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="显示边框">
                    <el-switch v-model="selectedItemData.border" />
                  </el-form-item>
                </template>
              </el-form>
            </div>
            <el-empty v-else description="请选择画布中的组件" />
          </el-tab-pane>

          <el-tab-pane label="数据" name="data">
            <div class="data-panel">
              <el-button type="primary" size="small" @click="handleBindData">
                绑定数据
              </el-button>
              <div v-if="selectedItemData?.datasource" class="data-info">
                <p>数据源: {{ selectedItemData.datasource }}</p>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="样式" name="style">
            <div class="style-panel">
              <el-form label-width="80px" size="small">
                <el-form-item label="背景色">
                  <el-color-picker v-model="canvasStyle.background" />
                </el-form-item>
                <el-form-item label="边距">
                  <el-input-number v-model="canvasStyle.padding" :min="0" :max="100" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- SQL查询对话框 -->
    <el-dialog v-model="sqlDialogVisible" title="新建SQL查询" width="800px">
      <el-form label-width="100px">
        <el-form-item label="查询名称">
          <el-input v-model="sqlForm.name" placeholder="请输入查询名称" />
        </el-form-item>
        <el-form-item label="SQL语句">
          <el-input 
            v-model="sqlForm.sql" 
            type="textarea" 
            :rows="10"
            placeholder="SELECT * FROM orders WHERE date > '2024-01-01'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="sqlDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveSQL">保存</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="报表预览" width="90%" fullscreen>
      <div class="preview-content">
        <div class="preview-canvas" :style="{ transform: `scale(1)` }">
          <div 
            v-for="item in canvasItems" 
            :key="item.id"
            :style="{
              position: 'absolute',
              left: item.x + 'px',
              top: item.y + 'px',
              width: item.width + 'px',
              height: item.height + 'px'
            }"
          >
            <div v-if="item.type === 'chart'" class="chart-preview">
              {{ item.chartType }} 图表预览
            </div>
            <div v-else-if="item.type === 'text'">
              {{ item.content }}
            </div>
            <div v-else-if="item.type === 'title'">
              <h2>{{ item.content }}</h2>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, markRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DocumentAdd, View, Download, RefreshLeft, RefreshRight, MagicStick,
  Document, Connection, Plus, Close,
  DataLine, PieChart, DataAnalysis, Grid,
  Document as DocIcon, Picture, Calendar
} from '@element-plus/icons-vue'

const reportName = ref('新建报表')
const activeTab = ref('datasource')
const rightTab = ref('properties')
const activeDatasource = ref(['1'])
const canvasSize = ref('a4-portrait')
const canvasZoom = ref(100)
const selectedItem = ref(null)
const sqlDialogVisible = ref(false)
const apiDialogVisible = ref(false)
const previewVisible = ref(false)

// 历史记录
const history = reactive({
  stack: [],
  current: -1
})

// 画布样式
const canvasStyle = reactive({
  background: '#ffffff',
  padding: 20
})

// 数据库表
const databaseTables = ref([
  { id: 1, name: '订单表(orders)', table: 'orders' },
  { id: 2, name: '产品表(products)', table: 'products' },
  { id: 3, name: '客户表(customers)', table: 'customers' }
])

// SQL查询
const sqlQueries = ref([
  { id: 1, name: '本月销售统计', sql: 'SELECT * FROM orders WHERE month = CURRENT_MONTH' }
])

const sqlForm = reactive({
  name: '',
  sql: ''
})

// 图表组件
const chartComponents = [
  { type: 'bar-chart', label: '柱状图', icon: markRaw(DataLine), chartType: 'bar' },
  { type: 'line-chart', label: '折线图', icon: markRaw(DataLine), chartType: 'line' },
  { type: 'pie-chart', label: '饼图', icon: markRaw(PieChart), chartType: 'pie' },
  { type: 'scatter-chart', label: '散点图', icon: markRaw(DataAnalysis), chartType: 'scatter' }
]

// 基础组件
const basicComponents = [
  { type: 'table', label: '表格', icon: markRaw(Grid) },
  { type: 'text', label: '文本', icon: markRaw(DocIcon) },
  { type: 'title', label: '标题', icon: markRaw(DocIcon) },
  { type: 'image', label: '图片', icon: markRaw(Picture) },
  { type: 'date', label: '日期', icon: markRaw(Calendar) }
]

// 画布项目
const canvasItems = ref([])

// 选中项数据
const selectedItemData = computed(() => {
  return canvasItems.value.find(item => item.id === selectedItem.value)
})

// 拖拽开始
const handleDragStart = (e, type, data) => {
  e.dataTransfer.effectAllowed = 'copy'
  e.dataTransfer.setData('type', type)
  e.dataTransfer.setData('data', JSON.stringify(data))
}

// 放置到画布
const handleDrop = (e) => {
  e.preventDefault()
  const type = e.dataTransfer.getData('type')
  const dataStr = e.dataTransfer.getData('data')
  
  if (!dataStr) return
  
  const data = JSON.parse(dataStr)
  
  const rect = e.currentTarget.getBoundingClientRect()
  const x = (e.clientX - rect.left) / (canvasZoom.value / 100)
  const y = (e.clientY - rect.top) / (canvasZoom.value / 100)
  
  let newItem = {
    id: Date.now(),
    type: type === 'chart' ? 'chart' : (type === 'component' ? data.type : type),
    x: Math.max(0, x - 50),
    y: Math.max(0, y - 25),
    width: 300,
    height: 200,
    chartType: data.chartType || 'bar',
    title: data.label || '标题',
    content: data.label || '内容',
    fontSize: 14,
    color: '#303133',
    border: true,
    datasource: '',
    columns: [
      { prop: 'id', label: 'ID' },
      { prop: 'name', label: '名称' }
    ],
    mockData: [
      { id: 1, name: '数据1' },
      { id: 2, name: '数据2' }
    ]
  }
  
  // 根据组件类型调整默认大小
  if (newItem.type === 'title') {
    newItem.height = 60
  } else if (newItem.type === 'text') {
    newItem.height = 100
  } else if (newItem.type === 'image') {
    newItem.width = 200
    newItem.height = 150
  }
  
  canvasItems.value.push(newItem)
  selectedItem.value = newItem.id
  ElMessage.success('添加组件成功')
}

// 选中项目
const handleSelectItem = (id) => {
  selectedItem.value = id
}

// 删除项目
const handleRemoveItem = (index) => {
  canvasItems.value.splice(index, 1)
  selectedItem.value = null
}

// 保存
const handleSave = () => {
  if (!reportName.value.trim()) {
    ElMessage.warning('请输入报表名称')
    return
  }
  
  const reportData = {
    name: reportName.value,
    canvasSize: canvasSize.value,
    canvasZoom: canvasZoom.value,
    canvasStyle: canvasStyle,
    items: canvasItems.value
  }
  
  console.log('保存报表:', reportData)
  localStorage.setItem('report_design', JSON.stringify(reportData))
  ElMessage.success('报表保存成功')
}

// 预览
const handlePreview = () => {
  if (canvasItems.value.length === 0) {
    ElMessage.warning('请先添加组件到画布')
    return
  }
  previewVisible.value = true
}

// 导出
const handleExport = () => {
  if (canvasItems.value.length === 0) {
    ElMessage.warning('请先添加组件到画布')
    return
  }
  
  ElMessageBox.confirm('请选择导出格式', '导出报表', {
    confirmButtonText: 'PDF',
    cancelButtonText: 'Excel',
    distinguishCancelAndClose: true,
    type: 'info'
  }).then(() => {
    ElMessage.success(`正在导出 ${reportName.value} 为PDF格式`)
  }).catch((action) => {
    if (action === 'cancel') {
      ElMessage.success(`正在导出 ${reportName.value} 为Excel格式`)
    }
  })
}

// 撤销
const handleUndo = () => {
  if (history.current > 0) {
    history.current--
    ElMessage.success('已撤销')
  }
}

// 重做
const handleRedo = () => {
  if (history.current < history.stack.length - 1) {
    history.current++
    ElMessage.success('已重做')
  }
}

// AI生成
const handleAIGenerate = () => {
  ElMessageBox.prompt('请描述您需要的报表内容', 'AI生成报表', {
    confirmButtonText: '生成',
    cancelButtonText: '取消',
    inputPlaceholder: '例如: 生成一个月度销售分析报表，包含销售趋势图和TOP10产品表格'
  }).then(({ value }) => {
    if (value) {
      // 模拟AI生成
      setTimeout(() => {
        // 添加标题
        canvasItems.value.push({
          id: Date.now(),
          type: 'title',
          x: 250,
          y: 30,
          width: 300,
          height: 60,
          content: '月度销售分析报表',
          fontSize: 24,
          color: '#303133'
        })
        
        // 添加图表
        setTimeout(() => {
          canvasItems.value.push({
            id: Date.now() + 1,
            type: 'chart',
            x: 50,
            y: 120,
            width: 350,
            height: 250,
            chartType: 'line',
            title: '销售趋势',
            datasource: 'orders'
          })
        }, 200)
        
        // 添加表格
        setTimeout(() => {
          canvasItems.value.push({
            id: Date.now() + 2,
            type: 'table',
            x: 420,
            y: 120,
            width: 350,
            height: 250,
            datasource: 'products',
            columns: [
              { prop: 'name', label: '产品名称' },
              { prop: 'sales', label: '销量' },
              { prop: 'amount', label: '销售额' }
            ],
            mockData: [
              { name: 'iPhone 15', sales: 145, amount: 869550 },
              { name: 'MacBook Pro', sales: 89, amount: 1780000 }
            ]
          })
        }, 400)
        
        ElMessage.success('AI报表生成成功！')
      }, 1500)
    }
  }).catch(() => {
    ElMessage.info('已取消生成')
  })
}

// 保存SQL
const handleSaveSQL = () => {
  if (!sqlForm.name.trim() || !sqlForm.sql.trim()) {
    ElMessage.warning('请填写查询名称和SQL语句')
    return
  }
  
  sqlQueries.value.push({
    id: Date.now(),
    name: sqlForm.name,
    sql: sqlForm.sql
  })
  
  sqlForm.name = ''
  sqlForm.sql = ''
  sqlDialogVisible.value = false
  ElMessage.success('SQL查询保存成功')
}

// 绑定数据
const handleBindData = () => {
  if (!selectedItemData.value) {
    ElMessage.warning('请先选择一个组件')
    return
  }
  ElMessage.info('数据绑定功能：选择数据源并配置字段映射')
}
</script>

<style scoped>
.report-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.designer-header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left, .header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.designer-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.designer-left {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.component-list {
  padding: 10px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  margin-bottom: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.component-item:hover {
  background: #e4e7ed;
  transform: translateX(5px);
}

.designer-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #e4e7ed;
  overflow: auto;
}

.canvas-toolbar {
  height: 50px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  padding: 0 20px;
  gap: 15px;
}

.canvas-area {
  flex: 1;
  margin: 20px auto;
  background: white;
  width: 794px;
  min-height: 1123px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  transform-origin: top center;
}

.canvas-item {
  position: absolute;
  border: 2px dashed transparent;
  cursor: move;
  transition: border-color 0.3s;
}

.canvas-item:hover,
.canvas-item.active {
  border-color: #409eff;
}

.item-remove {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 20px;
  height: 20px;
  background: #f56c6c;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.canvas-item:hover .item-remove,
.canvas-item.active .item-remove {
  opacity: 1;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 10px;
  height: 10px;
  background: #409eff;
  cursor: nwse-resize;
  opacity: 0;
  transition: opacity 0.3s;
}

.canvas-item:hover .resize-handle,
.canvas-item.active .resize-handle {
  opacity: 1;
}

.chart-placeholder,
.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

.item-text {
  padding: 10px;
}

.item-title h2 {
  margin: 0;
  padding: 10px;
  text-align: center;
}

.empty-canvas {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.designer-right {
  width: 320px;
  background: white;
  border-left: 1px solid #e4e7ed;
  overflow-y: auto;
}

.properties-panel,
.data-panel,
.style-panel {
  padding: 20px;
}

.preview-content {
  height: 100%;
  overflow: auto;
  background: #e4e7ed;
  padding: 20px;
}

.preview-canvas {
  width: 794px;
  min-height: 1123px;
  background: white;
  margin: 0 auto;
  position: relative;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>

